FROM python:3.8-slim as builder

# 设置工作目录
WORKDIR /app

# 将本地requirements.txt复制到容器中
COPY requirements.txt .

# 设置pip的超时时间
ENV PIP_DEFAULT_TIMEOUT=100

# 安装Python依赖，使用清华大学镜像源
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt

# 第二阶段：运行阶段
FROM python:3.8-slim

# 设置工作目录
WORKDIR /app

# 从构建阶段复制安装好的Python依赖
COPY --from=builder /usr/local/lib/python3.8/site-packages /usr/local/lib/python3.8/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# 创建日志目录并设置权限
RUN mkdir -p /app/logs && \
    chmod 777 /app/logs

# 创建健康检查接口
COPY health_check.py .

# 将本地代码复制到容器中
COPY *.py .

# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV LOG_LEVEL=INFO
ENV FETCH_INTERVAL=10
ENV KAFKA_SERVERS=kafka:9094
ENV HEALTH_CHECK_PORT=8000

# 暴露健康检查端口
EXPOSE 8000

# 容器启动时执行的命令
CMD ["python", "-u", "nowapi_gold_price.py"]

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
  CMD python -c "import requests; response = requests.get('http://localhost:8000/health'); exit(0) if response.status_code == 200 else exit(1)"